package com.yogi.webframework.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class GenericDaoHibernate<T, ID extends Serializable> implements
		GenericDao<T, Serializable> {

	private Class<T> clazz;
	@Autowired
	private SessionFactory sessionFactory;

	public void setClazz(final Class<T> clazzToSet) {
		clazz = clazzToSet;
	}

	protected final Session getCurrentSession() {
		System.out.println("******* get the current session");
		return sessionFactory.getCurrentSession();
	}

	@SuppressWarnings("unchecked")
	public T findById(Serializable id) {
		return (T) getCurrentSession().get(clazz, id);
	}

	public void save(T domain) {
		getCurrentSession().persist( domain );
	}

	public void delete(T domain) {
		getCurrentSession().delete( domain );
	}

	public Integer count() {		
		return findAll().size();
	}

	@SuppressWarnings("unchecked")
	public List<T> findAll() {
		return getCurrentSession()
			       .createQuery( "from " + clazz.getName() ).list();
	}

}
